package com.castle.fortress.admin.ai.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.ai.entity.AiRecordEntity;
import com.castle.fortress.admin.ai.service.AiRecordService;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.ai.entity.AiGroupEntity;
import com.castle.fortress.admin.ai.dto.AiGroupDto;
import com.castle.fortress.admin.ai.service.AiGroupService;
import com.castle.fortress.common.utils.ConvertUtil;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.admin.core.annotation.CastleLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.scan.AbstractInputStreamJar;
import springfox.documentation.annotations.ApiIgnore;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.castle.fortress.admin.utils.ExcelUtils;

import javax.servlet.http.HttpServletResponse;

import com.castle.fortress.common.entity.DynamicExcelEntity;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ai 组 控制器
 *
 * @author
 * @since 2024-03-09
 */
@Api(tags = "ai 组管理控制器")
@Controller
public class AiGroupController {
    @Autowired
    private AiGroupService aiGroupService;

    @Autowired
    private AiRecordService recordService;

    /**
     * ai 组的分页展示
     *
     * @param aiGroupDto ai 组实体类
     * @param current    当前页
     * @param size       每页记录数
     * @return
     */
    @CastleLog(operLocation = "ai 组", operType = OperationTypeEnum.QUERY)
    @ApiOperation("ai 组分页展示")
    @GetMapping("/ai/aiGroup/page")
    @ResponseBody
//    @RequiresPermissions("ai:aiGroup:pageList")
    public RespBody<IPage<AiGroupDto>> pageAiGroup(AiGroupDto aiGroupDto, @RequestParam(required = false) Integer current, @RequestParam(required = false) Integer size) {
        Integer pageIndex = current == null ? GlobalConstants.DEFAULT_PAGE_INDEX : current;
        Integer pageSize = size == null ? GlobalConstants.DEFAULT_PAGE_SIZE : size;
        Page<AiGroupDto> page = new Page(pageIndex, pageSize);
        IPage<AiGroupDto> pages = aiGroupService.pageAiGroup(page, aiGroupDto);

        return RespBody.data(pages);
    }

    /**
     * ai 组的列表展示
     *
     * @param aiGroupDto ai 组实体类
     * @return
     */
    @CastleLog(operLocation = "ai 组", operType = OperationTypeEnum.QUERY)
    @ApiOperation("ai 组列表展示")
    @GetMapping("/ai/aiGroup/list")
    @ResponseBody
    public RespBody<List<AiGroupDto>> listAiGroup(AiGroupDto aiGroupDto) {
        List<AiGroupDto> list = aiGroupService.listAiGroup(aiGroupDto);
        return RespBody.data(list);
    }

    /**
     * ai 组保存
     *
     * @param aiGroupDto ai 组实体类
     * @return
     */
    @CastleLog(operLocation = "ai 组", operType = OperationTypeEnum.INSERT)
    @ApiOperation("ai 组保存")
    @PostMapping("/ai/aiGroup/save")
    @ResponseBody
//    @RequiresPermissions("ai:aiGroup:save")
    public RespBody<AiGroupEntity> saveAiGroup(@RequestBody AiGroupDto aiGroupDto) {
        if (aiGroupDto == null) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        AiGroupEntity aiGroupEntity = ConvertUtil.transformObj(aiGroupDto, AiGroupEntity.class);
        aiGroupEntity.setCreateTime(new Date());
        aiGroupEntity.setUpdateTime(new Date());
        if (aiGroupService.save(aiGroupEntity)) {
            return RespBody.data(aiGroupEntity);
        } else {
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * ai 组编辑
     *
     * @param aiGroupDto ai 组实体类
     * @return
     */
    @CastleLog(operLocation = "ai 组", operType = OperationTypeEnum.UPDATE)
    @ApiOperation("ai 组编辑")
    @PostMapping("/ai/aiGroup/edit")
    @ResponseBody
//    @RequiresPermissions("ai:aiGroup:edit")
    public RespBody<String> updateAiGroup(@RequestBody AiGroupDto aiGroupDto) {
        if (aiGroupDto == null || aiGroupDto.getId() == null || aiGroupDto.getId().equals(0L)) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        AiGroupEntity aiGroupEntity = ConvertUtil.transformObj(aiGroupDto, AiGroupEntity.class);
        if (StrUtil.isEmpty(aiGroupDto.getName())) {
            aiGroupEntity.setUpdateTime(new Date());
        }
        if (aiGroupService.updateById(aiGroupEntity)) {
            return RespBody.data("保存成功");
        } else {
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * ai 组删除
     *
     * @param id
     * @return
     */
    @CastleLog(operLocation = "ai 组", operType = OperationTypeEnum.DELETE)
    @ApiOperation("ai 组删除")
    @PostMapping("/ai/aiGroup/delete")
    @ResponseBody
//    @RequiresPermissions("ai:aiGroup:delete")
    public RespBody<String> deleteAiGroup(@RequestParam Long id) {
        if (id == null) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        AiGroupEntity groupEntity = aiGroupService.getById(id);
        if (aiGroupService.removeById(id)) {
            if (groupEntity != null) {
                QueryWrapper<AiRecordEntity> aiRecordEntityQueryWrapper = new QueryWrapper<>();
                aiRecordEntityQueryWrapper.eq("user_id", groupEntity.getUserId());
                aiRecordEntityQueryWrapper.eq("group_id", id);
                List<AiRecordEntity> list = recordService.list(aiRecordEntityQueryWrapper);
                List<Long> collect = list.stream().map(AiRecordEntity::getId).collect(Collectors.toList());
                if (collect.size() > 0) {
                    recordService.removeByIds(collect);
                }
            }
            return RespBody.data("保存成功");
        } else {
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


    /**
     * ai 组批量删除
     *
     * @param ids
     * @return
     */
    @CastleLog(operLocation = "ai 组", operType = OperationTypeEnum.DELETE)
    @ApiOperation("ai 组批量删除")
    @PostMapping("/ai/aiGroup/deleteBatch")
    @ResponseBody
    @RequiresPermissions("ai:aiGroup:deleteBatch")
    public RespBody<String> deleteAiGroupBatch(@RequestBody List<Long> ids) {
        if (ids == null || ids.size() < 1) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if (aiGroupService.removeByIds(ids)) {
            return RespBody.data("保存成功");
        } else {
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * ai 组详情
     *
     * @param id ai 组id
     * @return
     */
    @CastleLog(operLocation = "ai 组", operType = OperationTypeEnum.QUERY)
    @ApiOperation("ai 组详情")
    @GetMapping("/ai/aiGroup/info")
    @ResponseBody
    @RequiresPermissions("ai:aiGroup:info")
    public RespBody<AiGroupDto> infoAiGroup(@RequestParam Long id) {
        if (id == null) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        AiGroupEntity aiGroupEntity = aiGroupService.getById(id);
        AiGroupDto aiGroupDto = ConvertUtil.transformObj(aiGroupEntity, AiGroupDto.class);

        return RespBody.data(aiGroupDto);
    }

    /**
     * 动态表头导出 依据展示的字段导出对应报表
     *
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
    @CastleLog(operLocation = "ai 组", operType = OperationTypeEnum.EXPORT)
    @PostMapping("/ai/aiGroup/exportDynamic")
    @ApiOperation("动态表头导出，依据展示的字段导出对应报表")
    public void exportDynamic(@RequestBody DynamicExcelEntity<AiGroupDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
        List<AiGroupDto> list = aiGroupService.listAiGroup(dynamicExcelEntity.getDto());
        //字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
        List<List<Object>> dataList = null;
        /**
         * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
         */
        ExcelUtils.exportDynamic(response, dynamicExcelEntity.getFileName() + ".xlsx", null, list, dynamicExcelEntity.getHeaderList(), dataList);
    }


}
